<?php
declare(strict_types=1);
/**
 * Created by PhpStorm
 * User: Administrator
 * Date: 2022/10/20
 * Time: 10:58:11
 */

namespace app\common\service\GoodsGroup;
use app\model\BbcModel\GoodsBrand;
use app\model\BbcModel\GoodsClass;
use app\model\BbcModel\GoodsGroup;
use app\model\BbcModel\GroupGoods;
use app\Normal;
use app\common\service\DecorateService\DecorateTabService;

class GoodsGroupService extends \app\BaseService
{
    public function lists(array $param){
        if(!isset($param['cid'])){
            return Normal::returnCode(Normal::FAIL,'缺少cid');
        }
        $page = (isset($param['page']) && $param['page'] != '') ? $param['page'] : 1;
        $limit = (isset($param['limit']) && $param['limit'] != '') ? $param['limit'] : 20;
        $where = [
            ['cid','=',$param['cid']],
            ['df','=',0],
        ];
        if(isset($param['status']) && $param['status'] != ''){
            $where[] = ['status','=',$param['status']];
        }
        $data_lists = GoodsGroup::instance()->where($where)->limit((int)$limit)->page((int)$page)->field('id,name,cd,status')->select()->toArray();
        foreach ($data_lists as $k=>$v){
            $goods_num = GroupGoods::instance()->alias('a')->join('goods b','b.id=a.goods_id')->where(['a.goods_group_id'=>$v['id'],'b.df'=>0])->count();
            $data_lists[$k]['goods_num'] = $goods_num;
            $data_lists[$k]['cd'] = date('Y-m-d H:i:s',$v['cd']);
        }
        $total = GoodsGroup::instance()->where($where)->count();
        return Normal::returnCode(Normal::SUC,'获取成功',['list'=>$data_lists,'total'=>$total]);
    }

    public function add(array $param){
        if(!isset($param['name']) || !$param['name']){
            return Normal::returnCode(Normal::FAIL,'名称不能为空');
        }
        $name = trim($param['name']);
        $s = GoodsGroup::instance()->info(['cid'=>$param['cid'],'name'=>$name,'df'=>0]);
        if($s){
            return Normal::returnCode(Normal::FAIL,'名称已存在');
        }
        $res = GoodsGroup::instance()->add(['cid'=>$param['cid'],'name'=>$name,'cd'=>time(),'cb_id'=>$param['cb_id']]);
        if($res == false){
            return Normal::returnCode(Normal::FAIL,'新增失败');
        }
        return Normal::returnCode(Normal::SUC,'新增成功');
    }

    public function edit( array $param) :array {
        if(!isset($param['id']) || !$param['id']){
            return Normal::returnCode(Normal::FAIL,'缺少商品分组ID');
        }
        if(!isset($param['name']) || !$param['name']){
            return Normal::returnCode(Normal::FAIL,'名称不能为空');
        }
        $info = GoodsGroup::instance()->where(['id'=>$param['id'],'cid'=>$param['cid'],'df'=>0])->find();
        if(!$info){
            return Normal::returnCode(Normal::FAIL,'商品分组不存在');
        }
        $s = GoodsGroup::instance()->where(['name'=>$param['name'],'df'=>0])->where('id','<>',$info['id'])->find();
        if($s){
            return Normal::returnCode(Normal::FAIL,'分组名称已存在');
        }
        $res = GoodsGroup::instance()->where(['id'=>$info['id']])->update(['name'=>$param['name'],'md'=>time()]);
        if($res == false){
            return Normal::returnCode(Normal::FAIL,'修改失败');
        }
        return Normal::returnCode(Normal::SUC,'编辑成功');
    }

    /**
     * 商品分组商品列表
     * @param array $param
     * @return void
     */
    public function goodsLists(array $param){
        $page = (isset($param['page']) && $param['page'] != '') ? $param['page'] : 1;
        $limit = (isset($param['limit']) && $param['limit'] != '') ? $param['limit'] : 20;
        if(!isset($param['id'])){
            return Normal::returnCode(Normal::FAIL,'缺少商品分组ID');
        }
        $info = GoodsGroup::instance()->info(['cid'=>$param['cid'],'id'=>$param['id']]);
        if(!$info){
            return Normal::returnCode(Normal::FAIL,'数据不存在');
        }

        $where = [
            ['cid','=',$param['cid']],
            ['a.goods_group_id','=',$param['id']],
            ['b.df','=',0]
        ];
        if(isset($param['goods_name']) && $param['goods_name'] != ''){
            $where[] = ['b.name','like',"%{$param['goods_name']}%"];
        }
        if(isset($param['skucode']) && $param['skucode'] != ''){
            $where[] = ['b.skucode','=',$param['skucode']];
        }
        if(isset($param['barcode']) && $param['barcode'] != ''){
            $where[] = ['b.barcode','=',$param['barcode']];
        }
        if(isset($param['origin']) && $param['origin'] != ''){
            $where[] = ['b.origin','=',$param['origin']];
        }
        if(isset($param['brand_name']) && $param['brand_name'] != ''){
            $brand_id = GoodsBrand::instance()->where(['cid'=>$param['cid'],'name'=>$param['brand_name'],'df'=>0])->value('id');
            $where[] = ['b.brand_id','=',$brand_id];
        }
        if(isset($param['class_id']) && $param['class_id'] != ''){
            $children = Goodsclass::instance()->where('pid', $param['class_id'])->where(['df'=>0])->column('id');
            $children_2 = GoodsClass::instance()->where('pid','in', $children)->where(['df'=>0])->column('id');
            $class_ids = array_merge($children,$children_2);
            array_push($class_ids,$param['class_id']);
            $where[]=['b.class_id','in',$class_ids];
        }
        //商品类型
        if(isset($param['is_bonded']) && $param['is_bonded'] !==''){
            $where[] = ['b.is_bonded', '=', $param['is_bonded']];
        }
        //品牌ID
        if(!empty($param['brand_id'])){
            $where[]=['b.brand_id','=',$param['brand_id']];
        }

        $data_lists = GroupGoods::instance()->alias('a')->join('goods b','b.id=a.goods_id')->where($where)->field('b.id,b.name,b.img,b.skucode,b.barcode,b.origin,b.brand_id,b.class_id,b.price,b.price_vip,b.price_market,b.price_cost,b.status')->limit((int)$limit)->page((int)$page)->select();
        foreach ($data_lists as $k=>$v){
            $class_name = GoodsClass::instance()->where(['id'=>$v['class_id']])->value('name');
            $brand_name = GoodsBrand::instance()->where(['id'=>$v['brand_id']])->value('name');
            $data_lists[$k]['class_name'] = $class_name;
            $data_lists[$k]['brand_name'] = $brand_name;
        }
        $total = GroupGoods::instance()->alias('a')->join('goods b','b.id=a.goods_id')->where($where)->count();
        return Normal::returnCode(Normal::SUC,'请求成功',['list'=>$data_lists,'total'=>$total]);
    }

    public function addGroupGoods(array $param){
        if(!isset($param['id']) || !$param['id']){
            return Normal::returnCode(Normal::FAIL,'缺少商品分组ID');
        }
        $info = GoodsGroup::instance()->where(['cid'=>$param['cid'],'id'=>$param['id']])->find();
        if(!$info){
            return Normal::returnCode(Normal::FAIL,'商品分组不存在');
        }
        if($info['status'] != 1){
            return Normal::returnCode(Normal::FAIL,'当前状态不能添加商品');
        }
        if(!isset($param['goods_ids']) || count($param['goods_ids']) <= 0){
            return Normal::returnCode(Normal::FAIL,'请选择商品');
        }
        GoodsGroup::instance()->startTrans();
        try{

            GroupGoods::instance()->where(['goods_group_id'=>$param['id']])->delete();
            foreach ($param['goods_ids'] as $k=>$v){
                $insertData[$k]['goods_group_id'] = $param['id'];
                $insertData[$k]['goods_id'] = $v;
            }
            GroupGoods::instance()->insertAll($insertData);
            GoodsGroup::instance()->commit();
        }catch (\Exception $e){
            GoodsGroup::instance()->rollback();
            return Normal::returnCode(Normal::FAIL,'添加失败'.$e->getMessage());
        }
        return Normal::returnCode(Normal::SUC,'添加成功');

    }

    /**
     * 移除商品
     * @return void
     */
    public function delGoods(array $param){
        if(!isset($param['goods_ids'])){
            return Normal::returnCode(Normal::FAIL,'请选择数据');
        }
        $info = GoodsGroup::instance()->where(['id'=>$param['id'],'cid'=>$param['cid']])->find();
        if(!$info){
            return Normal::returnCode(Normal::FAIL,'商品分组不存在');
        }
        $res = GroupGoods::instance()->where(['goods_group_id'=>$param['id']])->where('goods_id','in',$param['goods_ids'])->delete();
        if($res === false){
            return Normal::returnCode(Normal::FAIL,'移除成功');
        }
        return Normal::returnCode(Normal::SUC,'移除成功');
    }

    public function changeStatus( array $param): array{
        if(!isset($param['id']) || !$param['id']){
            return Normal::returnCode(Normal::FAIL,'ID为空');
        }
        if(!isset($param['status']) || !in_array($param['status'],[1,0])){
            return Normal::returnCode(Normal::FAIL,'状态参数错误');
        }
        $info = GoodsGroup::instance()->info(['id'=>$param['id'],'df'=>0,'cid'=>$param['cid']]);
        if(!$info){
            return Normal::returnCode(Normal::FAIL,'商品分组不存在');
        }
        if($param['status'] == 0){ //禁用
            $r = DecorateTabService::instance()->checkData($param);
            if(in_array($info['id'],$r['goods_group'])){
                return Normal::returnCode(Normal::FAIL,'商品组被使用无法禁用');
            }
        }
        $res = GoodsGroup::instance()->where(['id'=>$info['id']])->update(['md'=>time(),'status'=>$param['status']]);
        if($res == false){
            return Normal::returnCode(Normal::FAIL,'操作失败');
        }
        return Normal::returnCode(Normal::SUC,'操作成功');

    }

    public function delGoodsGroup( array $param): array{
        if(!isset($param['id']) || !$param['id']){
           return Normal::returnCode(Normal::FAIL,'缺少ID');
        }
        $info = GoodsGroup::instance()->info(['id'=>$param['id'],'cid'=>$param['cid'],'df'=>0]);
        if(!$info){
            return Normal::returnCode(Normal::FAIL,'商品分组不存在');
        }
        if($info['status'] == 1){
           return Normal::returnCode(Normal::FAIL,'当前状态不允许删除');
        }
        $r = DecorateTabService::instance()->checkData($param);
        if(in_array($info['id'],$r['goods_group'])){
            return Normal::returnCode(Normal::FAIL,'商品组被使用无法删除');
        }
        $res = GoodsGroup::instance()->where(['id'=>$param['id']])->update(['md'=>time(),'df'=>1]);
        if($res == false){
           return Normal::returnCode(Normal::FAIL,'删除失败');
        }
        return Normal::returnCode(Normal::SUC,'删除成功');
    }
}